package it.univpm.diiga.semanticsearch.gestione;

import it.univpm.diiga.semanticsearch.configurazione.Configuration;
import it.univpm.diiga.semanticsearch.servizi.Link;

import java.awt.Dimension;
import java.awt.Toolkit;

import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.ListSelectionModel;
import javax.swing.SpringLayout;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.ArrayList;

import javax.swing.JList;
import javax.swing.border.EtchedBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.JScrollPane;

import java.io.File;
import javax.swing.filechooser.FileFilter;




public class GestioneRepositoryView {

	/**
	 * 
	 */
	public static JDialog frmGestioneRepository;
	private JLabel lbl_list_title;
	private JButton btnAdd;
	private JButton btnModify;
	private JButton btnImport;
	private JButton btnDelete;
	private JScrollPane listPane;
	private JList list;
	private ListSelectionModel listSelectionModel;
	private DefaultListModel listModel;
	
	private JLabel wsdl_link;
	private JLabel selected_serv;
	private JLabel swsal_link;
	private JLabel bpel_link;
	private JLabel serv_link;
	private JLabel repo_link;
	private JLabel selected_serv2;
	private JLabel descr_serv;
	private JLabel meta_serv;
	private JPanel panel;
	
	private String localLink,localFormat;
	private ArrayList<Integer> selectedServ;	
	private ArrayList<Link> services;
	
	public GestioneRepository repomanager=null;
	
	private AddmodrepositoryView addmodView;
	
	
	/* Create the application.
	 */

	
	public GestioneRepositoryView() throws Exception {
		//try {
			Configuration.findLocalConfiguration();
			//localLink=((ArrayList<File>) Configuration.getConfiguration().get("localRepoLink")).get(0).toString();
			localLink=Configuration.getConfiguration().get("localRepoLink").toString();
			localFormat=(String) Configuration.getConfiguration().get("localRepoFormat");

		
		selectedServ=new ArrayList<Integer>();
				
		//repomanager = new GestioneRepository(localLink,localFormat);
		repomanager = new GestioneRepository();
		addmodView = new AddmodrepositoryView("",null,0,this); //preinizializzazione della maschera di aggiunta/modifica:
															   //nel costruttore essa richiede: Stringa modalità= "add" o "mod"
															   //			   				    Link ServDaModificare (null se in modo add)
															   //								int IndiceServ		  (0 se in modo add)
															   //							    gestioneRepositoryView repoview
															   //								  -->quest'ultimo è il riferimento all'intero
															   //									 frame principale, in modo da poter
															   //									 ripopolare la lista dopo le operazioni di modifica
		
		initialize();
		populateList();
		
		wsdl_link.setVisible(false);
		swsal_link.setVisible(false);
		bpel_link.setVisible(false);
		serv_link.setVisible(false);
		repo_link.setVisible(false);
		/*} catch (Exception e) {
			JOptionPane.showMessageDialog(null, "Wrong local file name or incomplete XML","Error", JOptionPane.ERROR_MESSAGE);
			//e.printStackTrace();
		}*/
		
	}




	public void populateList() throws Exception{
		
		//populate the list of services, reading them 
		//using readRepository method of gestioneRepository
	
		listModel.clear();
		services = repomanager.readRepository(localLink);
		
		if(services.size()>0){
		
			for(int i=0;i<services.size();i++){
				
				
				
				/*il codice seguente aggiunge alla Jlist il nome del servizio
				  affiancato dalle informazioni sui link e descrittori forniti(o meno)
				  con il servizio (wsdl,swsal,bpel, e link del servizio stesso)
				*/
				listModel.addElement(services.get(i).getServName());
				
				
			}
			
			lbl_list_title.setText("Services List (total entries: "+services.size()+")");
			selected_serv.setText("No service selected!");
	        selected_serv2.setVisible(false);
	        descr_serv.setVisible(false);
	        meta_serv.setVisible(false);
			
			
		}
		else{
		
		lbl_list_title.setText("Services List (total entries: "+services.size()+")");
		selected_serv.setText("No service found in local repository!");
		selected_serv2.setVisible(true);
		selected_serv2.setText("Please add or import new services.");		}
		descr_serv.setVisible(false);
        meta_serv.setVisible(false);
				
		
	}
	
	
	
	
	
	
	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frmGestioneRepository = new JDialog();
		frmGestioneRepository.setModal(true);
		frmGestioneRepository.setResizable(false);
		frmGestioneRepository.setTitle("Local Repository Managing");
		
		frmGestioneRepository.addWindowListener(new java.awt.event.WindowAdapter() {
		    public void windowClosing(WindowEvent winEvt) {
		        // Perhaps ask user if they want to save any unsaved files first.
		        addmodView.dispose();
		        frmGestioneRepository.dispose();

		    }
		});
		
		
		
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); //Gets screen resolution in a Dimension object
		int winw=654,winh=475;
		frmGestioneRepository.setBounds(((screenSize.width/2)-(winw/2)), ((screenSize.height/2)-(winh/2)), 654, 419); //Sets this frame position and size
		
		
	    //frmGestioneRepository.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		SpringLayout springLayout = new SpringLayout();
		frmGestioneRepository.getContentPane().setLayout(springLayout);
		{
			lbl_list_title = new JLabel("Found Services:");
			springLayout.putConstraint(SpringLayout.NORTH, lbl_list_title, 7, SpringLayout.NORTH, frmGestioneRepository.getContentPane());
			frmGestioneRepository.getContentPane().add(lbl_list_title);
		}
		{
			btnAdd = new JButton("Add");
			springLayout.putConstraint(SpringLayout.WEST, lbl_list_title, 0, SpringLayout.WEST, btnAdd);
			springLayout.putConstraint(SpringLayout.WEST, btnAdd, 10, SpringLayout.WEST, frmGestioneRepository.getContentPane());
			btnAdd.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					
					
				if (selectedServ.size()==1){					
						addmodView = new AddmodrepositoryView("add",null,selectedServ.get(0), GestioneRepositoryView.this);					
				}else{
						addmodView = new AddmodrepositoryView("add",null,-1, GestioneRepositoryView.this);
					}
				addmodView.setModal(true);
				addmodView.setVisible(true);
				
				}
			});
			frmGestioneRepository.getContentPane().add(btnAdd);
		}
		{
			listModel = new DefaultListModel();
			list = new JList(listModel);
			listSelectionModel = list.getSelectionModel();
	        listSelectionModel.addListSelectionListener(
	                new SharedListSelectionHandler());
	        listSelectionModel.setSelectionMode(
                    ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
	        
	        listPane = new JScrollPane(list); //scrollbar hooked to the list
	        
	        
			//springLayout.putConstraint(SpringLayout.SOUTH, lbl_title, -11, SpringLayout.NORTH, list);
			springLayout.putConstraint(SpringLayout.NORTH, btnAdd, 6, SpringLayout.SOUTH, listPane);
			springLayout.putConstraint(SpringLayout.NORTH, listPane, 23, SpringLayout.NORTH, frmGestioneRepository.getContentPane());
			springLayout.putConstraint(SpringLayout.SOUTH, listPane, -44, SpringLayout.SOUTH, frmGestioneRepository.getContentPane());
			springLayout.putConstraint(SpringLayout.EAST, listPane, -271, SpringLayout.EAST, frmGestioneRepository.getContentPane());
			springLayout.putConstraint(SpringLayout.WEST, listPane, 10, SpringLayout.WEST, frmGestioneRepository.getContentPane());
			
			listPane.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
			
			frmGestioneRepository.getContentPane().add(listPane);
		}
		{
			btnModify = new JButton("Modify");
			springLayout.putConstraint(SpringLayout.WEST, btnModify, 6, SpringLayout.EAST, btnAdd);
			springLayout.putConstraint(SpringLayout.SOUTH, btnModify, 0, SpringLayout.SOUTH, btnAdd);
			btnModify.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					
					
				if (selectedServ.size()==1){					
						addmodView = new AddmodrepositoryView("mod",services.get(selectedServ.get(0)),selectedServ.get(0), GestioneRepositoryView.this);
						addmodView.setModal(true);
						addmodView.setVisible(true);
				}else if(selectedServ.size()>1){
						JOptionPane.showMessageDialog(null,"You must select only the service you want to modify!","Modify Service",2);						
					}else{JOptionPane.showMessageDialog(null, "Select a service to modify first!","Modify Service",2);}
				
				
				
				}
			});			
			frmGestioneRepository.getContentPane().add(btnModify);
		}
		{
			btnDelete = new JButton("Delete");
			btnDelete.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					
					String message;					
					String title;
				
					if (selectedServ.size()>0){
						if(selectedServ.size()==1){
							message = "Do you really want to delete selected service\n from the local repository?\n"+
							"(Selected service: n. "+ (selectedServ.get(0)+1)+" - "+services.get(selectedServ.get(0)).getServName()+")";
							
						}else{
							message = "Do you really want to delete "+selectedServ.size()+" services\n from the local repository?\n"+
							"(Interval of selection: "+ (selectedServ.get(0)+1)+"-"+(selectedServ.get(selectedServ.size()-1)+1)+")";
						}
				        title = "Really Delete?";
				    // display the JOptionPane showConfirmDialog
				    int reply = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);
				    if (reply == JOptionPane.YES_OPTION)
				    {
				    	try {
							repomanager.delRepository(selectedServ);
							populateList();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							JOptionPane.showMessageDialog(null, "Wrong local file name or incomplete XML","Error", JOptionPane.ERROR_MESSAGE);
							//e.printStackTrace();
						}
				    	
				    	
				    }
					}else{ message = "Select a service to delete first!";
						   title = "Nothing to delete";
						   JOptionPane.showMessageDialog(null,message,title, JOptionPane.ERROR_MESSAGE);
					}
					

					
				}
			});
			springLayout.putConstraint(SpringLayout.NORTH, btnDelete, 0, SpringLayout.NORTH, btnAdd);
			springLayout.putConstraint(SpringLayout.WEST, btnDelete, 6, SpringLayout.EAST, btnModify);
			frmGestioneRepository.getContentPane().add(btnDelete);
		}
		{
			btnImport = new JButton("Import");
			btnImport.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					
					final JFileChooser fc = new JFileChooser();
					fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
					fc.setFileFilter(new XMLFileFilter());
					
			        int returnVal = fc.showOpenDialog(GestioneRepositoryView.frmGestioneRepository);
			        

			        if (returnVal == JFileChooser.APPROVE_OPTION) {
			            File file = fc.getSelectedFile();
			            try {
							repomanager.import_rep(file.getAbsolutePath());
							 populateList();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							JOptionPane.showMessageDialog(null, "Wrong local file name or incomplete XML","Error", JOptionPane.ERROR_MESSAGE);
							//e.printStackTrace();
						}
			          
			            
			        } else {
			        }
					
				}
			});
			springLayout.putConstraint(SpringLayout.NORTH, btnImport, 0, SpringLayout.NORTH, btnAdd);
			springLayout.putConstraint(SpringLayout.WEST, btnImport, 6, SpringLayout.EAST, btnDelete);
			
			frmGestioneRepository.getContentPane().add(btnImport);
		}
		{
			panel = new JPanel();
			springLayout.putConstraint(SpringLayout.NORTH, panel, 0, SpringLayout.NORTH, lbl_list_title);
			springLayout.putConstraint(SpringLayout.WEST, panel, 1, SpringLayout.EAST, listPane);
			springLayout.putConstraint(SpringLayout.SOUTH, panel, 0, SpringLayout.SOUTH, listPane);
			springLayout.putConstraint(SpringLayout.EAST, panel, 0, SpringLayout.EAST, frmGestioneRepository.getContentPane());
			frmGestioneRepository.getContentPane().add(panel);
			SpringLayout springLayout_1 = new SpringLayout();
			panel.setLayout(springLayout_1);
			panel.setBorder(BorderFactory.createTitledBorder("Details:"));
			{
				selected_serv = new JLabel("No service selected!");
				springLayout_1.putConstraint(SpringLayout.NORTH, selected_serv, 10, SpringLayout.NORTH, panel);
				springLayout_1.putConstraint(SpringLayout.WEST, selected_serv, 0, SpringLayout.WEST, panel);
				panel.add(selected_serv);
			}
			{
				wsdl_link = new JLabel("Wsdl link:");
				springLayout_1.putConstraint(SpringLayout.WEST, wsdl_link, 0, SpringLayout.WEST, selected_serv);
				panel.add(wsdl_link);
			}
			{
				swsal_link = new JLabel("Swsal link:");
				springLayout_1.putConstraint(SpringLayout.NORTH, swsal_link, 0, SpringLayout.SOUTH, wsdl_link);
				springLayout_1.putConstraint(SpringLayout.WEST, swsal_link, 0, SpringLayout.WEST, selected_serv);
				panel.add(swsal_link);
			}
			{
				bpel_link = new JLabel("Bpel link:");
				springLayout_1.putConstraint(SpringLayout.NORTH, bpel_link, 0, SpringLayout.SOUTH, swsal_link);
				springLayout_1.putConstraint(SpringLayout.WEST, bpel_link, 0, SpringLayout.WEST, selected_serv);
				panel.add(bpel_link);
			}
			{
				serv_link = new JLabel("Service link:");
				springLayout_1.putConstraint(SpringLayout.NORTH, serv_link, 22, SpringLayout.SOUTH, bpel_link);
				springLayout_1.putConstraint(SpringLayout.WEST, serv_link, 0, SpringLayout.WEST, selected_serv);
				//springLayout_1.putConstraint(SpringLayout.SOUTH, serv_link, -113, SpringLayout.SOUTH, panel);
				panel.add(serv_link);
			}
			{
				repo_link = new JLabel("Repository link:");
				springLayout_1.putConstraint(SpringLayout.NORTH, repo_link, 22, SpringLayout.SOUTH, serv_link);
				springLayout_1.putConstraint(SpringLayout.WEST, repo_link, 0, SpringLayout.WEST, selected_serv);
				panel.add(repo_link);
			}
			{
				selected_serv2 = new JLabel("Additional info.");
				springLayout_1.putConstraint(SpringLayout.NORTH, wsdl_link, 60, SpringLayout.SOUTH, selected_serv2);
				springLayout_1.putConstraint(SpringLayout.NORTH, selected_serv2, 0, SpringLayout.SOUTH, selected_serv);
				springLayout_1.putConstraint(SpringLayout.WEST, selected_serv2, 0, SpringLayout.WEST, selected_serv);
				panel.add(selected_serv2);
			}
			{
				descr_serv = new JLabel("Description: ");
				//springLayout_1.putConstraint(SpringLayout.NORTH, wsdl_link, 28, SpringLayout.SOUTH, descr_serv);
				springLayout_1.putConstraint(SpringLayout.NORTH, descr_serv, 2, SpringLayout.SOUTH, selected_serv2);
				springLayout_1.putConstraint(SpringLayout.WEST, descr_serv, 0, SpringLayout.WEST, selected_serv);
				panel.add(descr_serv);
			}
			{
				meta_serv = new JLabel("Meta-tag: ");
				springLayout_1.putConstraint(SpringLayout.NORTH, meta_serv, 1, SpringLayout.SOUTH, descr_serv);
				springLayout_1.putConstraint(SpringLayout.WEST, meta_serv, 0, SpringLayout.WEST, selected_serv);
				panel.add(meta_serv);
			}
		}
		{
			JButton btnClose = new JButton("Close");
			btnClose.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					addmodView.dispose();
					frmGestioneRepository.dispose();

				}
			});
			springLayout.putConstraint(SpringLayout.SOUTH, btnClose, 0, SpringLayout.SOUTH, btnAdd);
			springLayout.putConstraint(SpringLayout.EAST, btnClose, -10, SpringLayout.EAST, frmGestioneRepository.getContentPane());
			
			frmGestioneRepository.getContentPane().add(btnClose);
		}
	}
	
	
	class SharedListSelectionHandler implements ListSelectionListener {
	    public void valueChanged(ListSelectionEvent e) { 
	        ListSelectionModel lsm = (ListSelectionModel)e.getSource();

//	        int firstIndex = e.getFirstIndex();  	        									 
//	        int lastIndex = e.getLastIndex();	 
//	        boolean isAdjusting = e.getValueIsAdjusting(); 
	      /*  output.append("Event for indexes "
	                      + firstIndex + " - " + lastIndex
	                      + "; isAdjusting is " + isAdjusting
	                      + "; selected indexes:");
	*/
	        if (lsm.isSelectionEmpty()) {
	        	
	        	wsdl_link.setVisible(false);
	         	swsal_link.setVisible(false);
	         	bpel_link.setVisible(false);
	         	serv_link.setVisible(false);
	         	repo_link.setVisible(false);
	         	descr_serv.setVisible(false);
		        meta_serv.setVisible(false);
				
	            	  //          output.append(" <none>");
	         	
	        } else {
	            // Find out which indexes are selected.
	            int minIndex = lsm.getMinSelectionIndex();
	            int maxIndex = lsm.getMaxSelectionIndex();

	            //System.out.println(minIndex+" "+maxIndex);
	            
	            if (minIndex==maxIndex){ //selezione singola
	        	            	
	            			
	            	if(services.size()>0){
	            		
	            		
	            		selectedServ.clear();
	            		
	        			for(int i=0;i<services.size();i++){
	        				
	        				
	        				if(i==minIndex){
	        				/*il codice seguente legge i dettagli del servizio selezionato
	        				  e li scrive nelle label del pannello dei dettagli
	        				*/
	        				selected_serv.setText("Position: " + (minIndex+1));
	    	            	selected_serv2.setText("Serv. name: " + services.get(i).getServName());
	    	            	selected_serv2.setToolTipText(services.get(i).getServName());		
	    	            	
	    	            	
	    	            	if(services.get(i).getServDescr()!=null){
	    	            		descr_serv.setText("Description: " + services.get(i).getServDescr());
		    	            	descr_serv.setToolTipText(services.get(i).getServDescr());		
		    	           	}else{
		    	        		descr_serv.setText("Description: No description");
		    	            	descr_serv.setToolTipText(null);		
		    	            	}
	    	            	if(services.get(i).getServMeta().size()>0){
	    	            		String metatag="";
	    	            		for(int j=0;j<services.get(i).getServMeta().size();j++){
	    	            			if(j!=0) metatag+=", ";
	    	            			metatag+=services.get(i).getServMeta().get(j);
	    	            		}
	    	            		meta_serv.setText("Meta-tag: " + metatag);
		    	            	meta_serv.setToolTipText(metatag);		
		    	           	}else{
		    	        		meta_serv.setText("Meta-tag: No meta-tags avaiable");
		    	            	meta_serv.setToolTipText(null);		
		    	            	}
	    	            	
	    	            	
	    	            	
	    	            	if(services.get(i).getWsdlLink()!=null){
	    	            	wsdl_link.setText("Wsdl link: "+  services.get(i).getWsdlLink());
	    	            	wsdl_link.setToolTipText(services.get(i).getWsdlLink());
	    	            	}else{
	    	            		wsdl_link.setText("Wsdl link: Not specified");
	    	            		wsdl_link.setToolTipText(null);
	    	            	}
	    	            	
	    	            	if(services.get(i).getSwsalLink()!=null){		    	            	
	    	            	swsal_link.setText("Swsal link: " + services.get(i).getSwsalLink());
	    	            	swsal_link.setToolTipText("Swsal link: " + services.get(i).getSwsalLink());
	    	            	}else{
	    	            		swsal_link.setText("Swsal link: Not specified");
	    	            		swsal_link.setToolTipText(null);
	    	            	}	
	    	            	
	    	            	if(services.get(i).getBpellLink()!=null){		    	            	
	    	            	bpel_link.setText("Bpel link: " + services.get(i).getBpellLink());
	    	            	bpel_link.setToolTipText(services.get(i).getBpellLink());
	    	            	}else{
	    	            		bpel_link.setText("Bpel link: Not specified");
	    	            		bpel_link.setToolTipText(null);
	    	            	}
	    	            	
	    	            	if(services.get(i).getServLink()!=null){		    	            	
	    	            	serv_link.setText("Service link: " + services.get(i).getServLink());
	    	            	serv_link.setToolTipText(services.get(i).getServLink());
	    	            	}else{
	    	            		serv_link.setText("Service link: Not specified");
	    	            		serv_link.setToolTipText(null);	    	            		
		    	            }
	    	            	
	    	            	if(services.get(i).getServRepo()!=null){		    	            	
	    	            	repo_link.setText("Repository link: " + services.get(i).getServRepo());
	    	            	repo_link.setToolTipText(services.get(i).getServRepo());
	    	            	}else{
	    	            		repo_link.setText("Repository link: Not specified");
	    	            		repo_link.setToolTipText(null);	    	            		
	    	            	}
	    	            	
	    	            	selected_serv2.setVisible(true);
	    	            	wsdl_link.setVisible(true);
	    	            	swsal_link.setVisible(true);
	    	            	bpel_link.setVisible(true);
	    	            	serv_link.setVisible(true);
	    	            	repo_link.setVisible(true);
	    	            	descr_serv.setVisible(true);
	    	    	        meta_serv.setVisible(true);
	    	    			
	    	            	
	    	            	selectedServ.add(i); //indica il servizio iesimo come selezionato
	    	            	
	        				}
	        				
	       				}		
	           		}
	            	
	            	
	     }else{
	            	
	    	
         	
         	selectedServ.clear();
	            for (int i = minIndex; i <= maxIndex; i++) {
	                if (lsm.isSelectedIndex(i)) {
	                	
	                	selectedServ.add(i);
	            //        System.out.println(" " + i);
	                }
	            }
	            
	            
	            selected_serv.setText("Multiple services Selected!");
	         	selected_serv2.setText("("+selectedServ.size()+" elems. between service " +(minIndex+1)+" and "+(maxIndex+1)+")");
	         	selected_serv2.setToolTipText(selectedServ.size()+" services selected between service " +(minIndex+1)+" and "+(maxIndex+1));
	         	
	         	wsdl_link.setVisible(false);
	         	swsal_link.setVisible(false);
	         	bpel_link.setVisible(false);
	         	serv_link.setVisible(false);
	         	repo_link.setVisible(false);
	         	descr_serv.setVisible(false);
		        meta_serv.setVisible(false);
				
	            
	            }
	        }
	        //output.append(newline);
	        //output.setCaretPosition(output.getDocument().getLength());
	    }
	}
}










